<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class User_m extends MY_Model
{
    const TBL = "users";
    const UNIQUE_KEY = "user_id";

    function __construct()
    {
        parent::__construct();
    }

    function get_user_by_user_id($user_id)
    {
        $query = $this->db->select('*')->from(self::TBL)->where('user_id', $user_id)->get();
        return $query->row_array();
    }

    function get_user_by_user_code($user_code)
    {
        $query = $this->db->select('*')->from(self::TBL)->where('user_code', $user_code)->get();
        return $query->row_array();
    }

    function get_user_by_user_code_group($user_code, $group)
    {
        $query = $this->db->select('*')->from(self::TBL)->where('user_code', $user_code)->where('user_group', $group)->get();
        return $query->row_array();
    }

    function get_user_by_user_id_by_group($user_id, $group)
    {
        $query = $this->db->select('*')->from(self::TBL)->where('user_id', $user_id)->where('user_group', $group)->get();
        return $query->row_array();
    }

    function get_user_by_user_key($user_key)
    {
        $query = $this->db->select('user_id,user_key_expire')->from(self::TBL)->where('user_key', $user_key)->get();
        return $query->row_array();
    }

    function get_user_by_user_id_group($user_id)
    {
        $query = $this->db->select('a.*,b.*')->from('users a')->join('auth_groups b', 'b.id=a.user_group', 'LEFT')->where('a.user_id', $user_id)->get();
        return $query->row_array();
    }

    function get_user_by_username($user_name)
    {
        $query = $this->db->select('*')->from(self::TBL)->where('user_name', $user_name)->or_where('user_tel', $user_name)->get();
        return $query->row_array();
    }

    function get_user_by_username_by_group($user_name, $group)
    {
        $query = $this->db->select('*')->from(self::TBL)->group_start()->where('user_name', $user_name)->or_where('user_tel', $user_name)->group_end()->where('user_group', $group)->get();
        return $query->row_array();
    }

    function get_user_by_username_group($user_name)
    {
        $query = $this->db->select('a.*,b.*')->from('users a')->join('auth_groups b', 'b.id=a.user_group', 'LEFT')->where('a.user_name', $user_name)->or_where('a.user_tel', $user_name)->get();
        return $query->row_array();
    }

    function get_user_by_user_group($user_group)
    {
        $query = $this->db->select('title')->from('auth_groups')->where('id', $user_group)->get();
        $info  = $query->row_array();
        if ($info) {
            return $info['title'];
        } else {
            return '未知';
        }
    }

    function register($data)
    {
        return $this->db->insert(self::TBL, $data);
    }

    function login($data, $group = 0)
    {
        if ($group > 0) {
            $user = $this->get_user_by_username_by_group($data['user_name'], $group);
        } else {
            $user = $this->get_user_by_username($data['user_name']);
        }
        if ($user) {
            $password = password_dohash($data['user_password'], $user['user_salt']);
            if ($user['user_password'] == $password) {
                $this->session->set_userdata('user_id', $user['user_id']);
                $loveme = password_dohash($user['user_id'], $user['user_salt']);
                if ($loveme) {
                    $_COOKIE['loveme'] = $loveme;
                    setcookie('loveme', $loveme, time() + 86500, '/', '', false, true);
                    $this->user_m->update_user($user['user_id'], ['user_key' => $loveme]);
                }
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    function checklogin($key, $salt)
    {
        $user = $this->user_m->get_user_by_user_key($key);
        if ($user) {
            $this->session->set_userdata('user_id', $user['user_id']);
            $loveme = password_dohash($user['user_id'], $salt);
            if ($loveme) {
                $_COOKIE['loveme'] = $loveme;
                setcookie('loveme', $loveme, time() + 86500, '/', '', false, true);
                $this->user_m->update_user($user['user_id'], ['user_key' => $loveme]);
            }
        }
    }

    function check_ulock($username)
    {
        $query = $this->db->select('user_lock')->from(self::TBL)->where('user_name', $username)->or_where('user_tel', $username)->get();
        $ulock = $query->row_array();
        if ($ulock['user_lock'] == 0) {
            return true;
        } else {
            return false;
        }
    }

    function check_register_username($user_name)
    {
        $query = $this->db->get_where(self::TBL, ['user_name' => $user_name]);
        return $query->row_array();
    }

    function update_user($uid, $data)
    {
        $this->db->where('user_id', $uid);
        $this->db->update(self::TBL, $data);
        return ($this->db->affected_rows() > 0) ? true : false;
    }

    public function update_credit($uid, $credit)
    {
        $this->db->set('user_credit', 'user_credit+' . $credit, false)->where('user_id', $uid)->update(self::TBL);
        return ($this->db->affected_rows() > 0) ? true : false;
    }

    public function del_user_key_by_user_id($uid)
    {
        $this->db->set('user_key', time(), false)->where('user_id', $uid)->update(self::TBL);
        return ($this->db->affected_rows() > 0) ? true : false;
    }

    function get_user_with_group($uid)
    {
        $sql   = "SELECT * FROM {$this->db->dbprefix}auth_groups g left join {$this->db->dbprefix}auth_group_access a on g.id=a.group_id where a.uid=$uid";
        $query = $this->db->query($sql);
        return $query->row_array();
    }

    public function get_user_group_rule_list()
    {
        $this->db->select('users.*,auth_groups.id as gid,auth_groups.title');
        $this->db->from('fox_users');
        $this->db->join('auth_group_access', 'users.user_id = auth_group_access.uid', 'left');
        $this->db->join('auth_groups', 'auth_groups.id = auth_group_access.group_id', 'left');
        $this->db->order_by('users.user_id', 'desc');
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            return $query->result_array();
        }
    }

    public function count_user_search($user_group = null, $register_status = null, $user_dress = null, $user_name = null)
    {
        $this->db->select('user_id');
        $this->db->from(self::TBL);
        if ($user_group) {
            if ($user_group == 1) {
                $this->db->where_in("users.user_group", [1, 2, 7]);
            } else {
                $this->db->where("users.user_group", $user_group);
            }
        } else {
            $this->db->where("users.user_group !=", 1);
        }
        if ($register_status) {
            $this->db->where("users.register_status", $register_status);
        }
        if ($user_dress) {
            $this->db->where("users.user_dress", $user_dress);
        }
        if ($user_name) {
            $this->db->where("users.user_name", $user_name);
        }
        $total = $this->db->count_all_results();
        return $total;
    }

    //翻页及搜索
    public function get_user_group_rule_list_search_ord($start, $limit, $order, $user_group = null, $register_status = null, $user_dress = null, $user_name = null)
    {
        $this->db->select('users.*,auth_groups.id as gid,auth_groups.title');
        $this->db->from('fox_users');
        if ($user_group) {
            if ($user_group == 1) {
                $this->db->where_in("users.user_group", [1, 2, 7]);
            } else {
                $this->db->where("users.user_group", $user_group);
            }
        } else {
            $this->db->where("users.user_group !=", 1);
        }
        if ($register_status) {
            $this->db->where("users.register_status", $register_status);
        }
        if ($user_dress) {
            $this->db->where("users.user_dress", $user_dress);
        }
        if ($user_name) {
            $this->db->where("users.user_name", $user_name);
        }
        $this->db->join('auth_group_access', 'users.user_id = auth_group_access.uid', 'left');
        $this->db->join('auth_groups', 'auth_groups.id = auth_group_access.group_id', 'left');
        $this->db->order_by('users.user_regtime', $order);
        $this->db->limit($limit, $start);
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            return $query->result_array();
        }
    }

    /**
     * 判断号码是否已注册
     * @param $mobile
     * @return bool
     */
    public function is_mobile_registered($mobile)
    {

        $this->db->select('*');
        $this->db->where("user_tel", $mobile);
        $this->db->from(self::TBL);
        $query = $this->db->get();
        return $query->row_array();
    }

    public function is_mobile_registered_group($mobile, $group)
    {

        $this->db->select('*');
        $this->db->where("user_tel", $mobile);
        $this->db->where("user_group", $group);
        $this->db->from(self::TBL);
        $query = $this->db->get();
        return $query->row_array();
    }

    public function update_user_avatar($user_id, $data)
    {
        $this->db->where('user_id', $user_id);
        $this->db->update(self::TBL, $data);
        return ($this->db->affected_rows() > 0) ? true : false;
    }

    //修改用户生日
    public function update_user_birth($user_id, $data)
    {
        $this->db->where('user_id', $user_id);
        $this->db->update(self::TBL, $data);
        // echo $this->db->last_query();
        return ($this->db->affected_rows() > 0) ? true : false;
    }

    public function get_username_by_utel($utel)
    {
        $query = $this->db->select('user_name')->from(self::TBL)->where('user_tel', $utel)->get();
        return $query->row_array();
    }

    //查找用户是否绑定QQ
    public function get_qq_user_by_id($user_id)
    {
        $this->db->select('*');
        $this->db->from('qq_users');
        $this->db->where('user_id', $user_id);
        $query = $this->db->get();
        return $query->row_array();
    }

    //查找微信用户
    public function get_wx_user_by_id($user_id)
    {
        $this->db->select('*');
        $this->db->from('weixin_users');
        $this->db->where('user_id', $user_id);
        $query = $this->db->get();
        return $query->row_array();
    }

    //查找微博登录
    public function get_wb_user_by_id($user_id)
    {
        $this->db->select('*');
        $this->db->from('weibo_users');
        $this->db->where('user_id', $user_id);
        $query = $this->db->get();
        return $query->row_array();
    }

    //查询用户的注册手机号
    public function get_user_tel_by_id($user_id)
    {
        $this->db->select('user_tel');
        $this->db->from(self::TBL);
        $this->db->where('user_id', $user_id);
        $query = $this->db->get();
        return $query->row_array();
    }

    //寻找默认地址
    function get_address_by_uid($user_id)
    {
        $query = $this->db->select('*')->from('user_dress')->where('dress_type', 1)->where('user_id', $user_id)->get();
        return $query->result_array();
    }

    /**
     * @param $where
     * @return bool
     * 删除用户
     */
    public function delete_shop_users_by($where)
    {
        $this->db->where($where)->delete(self::TBL);
        return ($this->db->affected_rows() > 0) ? true : false;
    }

    //查询所有的用户
    public function get_all_users()
    {
        $query = $this->db->select('user_id,user_name')->from(self::TBL)->where('user_group', 4)->order_by('user_id', 'desc')->get();
        if ($query->num_rows() > 0) {
            return $query->result_array();
        }
    }

    // 获取所有在产生收益的用户
    public function get_all_users_with_return()
    {

        $this->db->select('user_id,today_free_num,today_return_num');
        $this->db->from(self::TBL);
        $this->db->where('today_return_num > ', 0);
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            return $query->result_array();
        }
    }

    public function get_user_money_by_uid($chong_user_id)
    {
        $query  = $this->db->select('user_money')->from(self::TBL)->where('user_id', $chong_user_id)->get();
        $result = $query->row_array();
        return $result['user_name'];
    }

    public function api_login($user_name, $user_pass)
    {
        $user = $this->get_user_by_username($user_name);
        if ($user) {
            $password = password_dohash($user_pass, $user['user_salt']);
            if ($user['user_password'] == $password) {
                $token = sha1(md5(uniqid(md5(microtime(true)), true)));
                if ($token) {
                    $this->user_m->update_user($user['user_id'], ['user_key' => $token, 'user_key_expire' => time() + 2592000, 'user_logtime' => time()]);
                }
                return $this->get_user_by_user_id($user['user_id']);
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 基本注册信息
     * @param $data
     * @return bool
     */
    public function api_register($data)
    {
        $user_data = [
            'user_birth'            => $data['user_birth'] ?? "",
            'user_uname'            => $data['user_uname'] ?? "",
            'user_key'              => $data['user_key'] ?? "",
            'user_email'            => $data['user_email'] ?? "",
            'user_sex'              => $data['user_sex'] ?? "",
            'user_tel'              => $data['user_tel'] ?? "",
            'user_urgent_tel'       => $data['user_urgent_tel'] ?? "",
            'user_wechat'           => $data['user_wechat'] ?? "",
            'user_district'         => $data['user_district'] ?? "",
            'user_dress'            => $data['user_dress'] ?? "",
            'user_service_type'     => $data['user_service_type'] ?? "",
            'user_self_desc'        => $data['user_self_desc'] ?? "",
            'user_guide_number'     => $data['user_guide_number'] ?? "",
            'is_association_member' => $data['is_association_member'] ?? "",
            'association_member'    => $data['association_member'] ?? "",
            'register_status'       => 2,
            'user_group'            => $data['user_service_type'] ?? 3,
            'user_editime'          => time(),
        ];
        $this->user_m->update_user($data['user_id'], $user_data);
        if ($this->db->affected_rows() > 0) {
            return $data['user_id'];
        } else {
            return false;
        }
    }

    /**
     * 汽车信息完善
     * @param $data
     * @return bool
     */
    public function api_car_register($data)
    {
        if ($data) {
            $car_info = [
                'user_id'             => $data['user_id'],
                'drive_card_no'       => $data['drive_card_no'] ?? "",
                'get_drive_card_time' => $data['get_drive_card_time'] ?? "",
                'car_brand_id'        => $data['car_brand_id'] ?? "",
                'car_type'            => $data['car_type'] ?? "",
                'car_seat'            => $data['car_seat'] ?? "",
                'car_drive_time'      => $data['car_drive_time'] ?? "",
                'car_no'              => $data['car_no'] ?? "",
                'road_access'         => $data['road_access'] ?? "",
                'car_imgs'            => $data['car_imgs'] ?? "",
            ];
            $this->db->insert('car_info', $car_info);
            $car_id = $this->db->insert_id();
            if ($car_id) {
                $this->user_m->update_user($data['user_id'], ['register_status' => 3]);
                return $car_id;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    /**
     * 钱包信息完善
     * @param $data
     * @return bool
     */
    public function api_wallet_register($data)
    {
        if ($data) {
            $wallet_info = [
                'type'      => $data['type'],
                'account'   => $data['account'] ?? "",
                'user_name' => $data['user_name'] ?? "",
                'bank'      => $data['bank'] ?? "",
                'user_id'   => $data['user_id'],
            ];
            $this->db->insert('wallet_info', $wallet_info);
            $wallet_id = $this->db->insert_id();
            if ($wallet_id) {
                $this->user_m->update_user($data['user_id'], ['register_status' => 4]);
                return $wallet_id;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    /**
     * 用户名查找，同名
     * @param $user_name
     * @return mixed
     */
    function get_user_by_user_name($user_name)
    {
        $query = $this->db->select('*')->from(self::TBL)->where('user_name', $user_name)->get();
        return $query->row_array();
    }

    /**
     * 账号密码注册
     * @param $data
     * @return bool
     */
    public function api_register_base($data)
    {
        $user_data = [
            'user_name'       => $data['user_name'] ?? "",
            'user_password'   => $data['user_password'] ?? "",
            'user_salt'       => $data['user_salt'] ?? "",
            'register_status' => 1,
            'user_regtime'    => time(),

        ];
        $this->db->insert(self::TBL, $user_data);
        if ($this->db->affected_rows() > 0) {
            $user_id = $this->db->insert_id();
            if ($user_id) {
                return $user_id;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    /**
     * 账号密码修改
     * @param $data
     * @return bool
     */
    public function api_modify_base($data)
    {
        $user_data = [
            'user_name'       => $data['user_name'] ?? "",
            'user_password'   => $data['user_password'] ?? "",
            'user_salt'       => $data['user_salt'] ?? "",
            'user_editime'    => time(),
            'register_status' => 4,
        ];
        return $this->update(['user_id' => $data['user_id']], $user_data);
    }

    /**
     * 修改基本信息
     * @param $data
     * @return bool
     */
    public function api_modify($data)
    {
        $user_data = [
            'user_birth'            => $data['user_birth'] ?? "",
            'user_uname'            => $data['user_uname'] ?? "",
            'user_email'            => $data['user_email'] ?? "",
            'user_sex'              => $data['user_sex'] ?? "",
            'user_tel'              => $data['user_tel'] ?? "",
            'user_urgent_tel'       => $data['user_urgent_tel'] ?? "",
            'user_wechat'           => $data['user_wechat'] ?? "",
            'user_district'         => $data['user_district'] ?? "",
            'user_dress'            => $data['user_dress'] ?? "",
            'user_service_type'     => $data['user_service_type'] ?? "",
            'user_self_desc'        => $data['user_self_desc'] ?? "",
            'user_guide_number'     => $data['user_guide_number'] ?? "",
            'is_association_member' => $data['is_association_member'] ?? "",
            'association_member'    => $data['association_member'] ?? "",
            'user_editime'          => time(),
            'register_status'       => 4,
        ];
        return $this->update(['user_id' => $data['user_id']], $user_data);
    }

    public function get_push_users($departure_city, $order_type, $seat_ids = [])
    {
        $this->db->select('users.user_id,apns.device_token');
        $this->db->from("users");
        $this->db->where('users.user_group', $order_type);
        $this->db->where('users.user_dress', $departure_city);
        if (!empty($seat_ids)) {
            // 司导订单
            $this->db->join('car_info', 'car_info.user_id = users.user_id', 'left');
            $this->db->where_in('car_info.car_seat', $seat_ids);
        }
        $this->db->join('apns', 'users.user_id = apns.user_id', 'left');
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            return $query->result_array();
        }
    }

    public function get_users_by_service_type($service_id)
    {
        $this->db->select('users.user_id,users.user_name');
        $this->db->from("users");
        $this->db->where('users.user_service_type', $service_id);
        $this->db->where("users.user_group !=", 1);
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            return $query->result_array();
        }
    }

    public function get_user_group_rule_list_export($user_group = null, $user_dress = null)
    {
        $this->db->select('users.*,auth_groups.id as gid,auth_groups.title');
        $this->db->from('fox_users');
        if ($user_group) {
            if ($user_group == 1) {
                $this->db->where_in("users.user_group", [1, 2, 7]);
            } else {
                $this->db->where("users.user_group", $user_group);
            }
        } else {
            $this->db->where("users.user_group !=", 1);
        }

        if ($user_dress) {
            $this->db->where("users.user_dress", $user_dress);
        }
        $this->db->join('auth_group_access', 'users.user_id = auth_group_access.uid', 'left');
        $this->db->join('auth_groups', 'auth_groups.id = auth_group_access.group_id', 'left');
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            return $query->result_array();
        }
    }
}
